﻿using AVCUMPlatform.Entities;
using AVCUMPlatform.HelperLibrary;
using AVCUMPlatform.WXService.Interface;
using AVCUMPlatform.WXService.Model;
using Newtonsoft.Json;
using System;

namespace AVCUMPlatform.WXService.Service
{
    /// <summary>
    /// 微信接口访问工具类
    /// </summary>
    public class WXService : IWXPlatformApiHelper
    {
        /// <summary>
        /// appid
        /// </summary>
        private string _appid { get; set; }
        /// <summary>
        /// appSecret
        /// </summary>
        private string _appSecret { get; set; }
        /// <summary>
        /// 客户端地址
        /// </summary>
        private string _clientHost { get; set; }
        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="appSecret"></param>
        /// <param name="clientHost"></param>
        public WXService(string appid, string appSecret, string clientHost)
        {
            _appid = appid;
            _appSecret = appSecret;
            _clientHost = clientHost;
        }

        /// <summary>
        /// 获取所有微信消息模板
        /// </summary>
        /// <returns></returns>
        public AllPrivateTemplates GetAllPrivateTemplate() 
        {
            try
            {
                string token = WXToken.GetInstance(_appid, _appSecret).AccessToken;
                string url = $"https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token={token}";
                return HTTPHelper.Get<AllPrivateTemplates>(url);
            }
            catch (Exception ex)
            {
                Log.WriteException(ex);
                return null;
            }
        }

        /// <summary>
        /// 发布菜单
        /// </summary>
        public WXRes PublishMenu(string firstMenuName)
        {
            try
            {
                string token = WXToken.GetInstance(_appid, _appSecret).AccessToken;
                string url = $"https://api.weixin.qq.com/cgi-bin/menu/create?access_token={token}";
                List<WXButton> buttons = GetMenu(firstMenuName);
                var param = new
                {
                    button = buttons
                };
                return HTTPHelper.Post<WXRes>(url, param);
            }
            catch (Exception)
            {
                throw;
            }
        }

        /// <summary>
        /// 获取微信菜单
        /// </summary>
        /// <returns></returns>
        private List<WXButton> GetMenu(string firstMenuName)
        {
            List<WXButton> buttons = new List<WXButton>();
            buttons.Add(new WXButton
            {
                type = "view",
                name = firstMenuName,
                url = $"https://open.weixin.qq.com/connect/oauth2/authorize?appid={_appid}&redirect_uri={_clientHost}&response_type=code&scope=snsapi_base&state=123#wechat_redirect",
                sub_button = new List<WXButton>()
            });
            return buttons;
        }

        /// <summary>
        /// 获取访问授权码/openid
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public WXAccessToken GetAccesstoken(string code)
        {
            string url = $"https://api.weixin.qq.com/sns/oauth2/access_token?appid={_appid}&secret={_appSecret}&code={code}&grant_type=authorization_code";
            return HTTPHelper.Get<WXAccessToken>(url);
        }

        /// <summary>
        /// 获取unionid
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public GetWXUnionid GetWXUnionid(string code)
        {
            string url = $"https://api.weixin.qq.com/sns/oauth2/access_token?appid={_appid}&secret={_appSecret}&code={code}&grant_type=authorization_code";
            WXAccessToken accessToken = HTTPHelper.Get<WXAccessToken>(url);
            url = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={_appid}&secret={_appSecret}";
            GetOverAllToken overToken = HTTPHelper.Get<GetOverAllToken>(url);
            url = $"https://api.weixin.qq.com/cgi-bin/user/info?access_token={overToken.access_token}&openid={accessToken.openid}&lang=zh_CN";
            //url = $"https://api.weixin.qq.com/sns/userinfo?access_token={accessToken.access_token}&openid={accessToken.openid}&lang=zh_CN";
            GetWXUnionid getWXUnionid = HTTPHelper.Get<GetWXUnionid>(url);
            return getWXUnionid;
        }

        /// <summary>
        /// 发送模板消息
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public SendTemplateMsgRes SendTemplateMsg(WXTemplateMsgRM data)
        {
            try
            {
                //Log.Write($"requestParam:{JsonConvert.SerializeObject(data)}");
                string token = WXToken.GetInstance(_appid, _appSecret).AccessToken;
                string url = $"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={token}";
                SendTemplateMsgRes sendTemplateMsgRes = HTTPHelper.Post<SendTemplateMsgRes>(url, data);
                if (sendTemplateMsgRes.msgid == null)
                {

                    token = WXToken.GetInstance(_appid, _appSecret).RefreshToken();
                    url = $"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={token}";
                    sendTemplateMsgRes = HTTPHelper.Post<SendTemplateMsgRes>(url, data);
                }
                return sendTemplateMsgRes;
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}